#include "WorkThreadManage/servercommange.h"

HmiServer :: HmiServer(){
    this->pRobControllerHMI = nullptr;
    this->pTecControllerHMI = nullptr;

    this->pHmiRobServer = new QTcpServer();
    this->pHmiRobServer->listen(QHostAddress::Any, 1204);

    this->pHmiTecServer = new QTcpServer();
    this->pHmiTecServer->listen(QHostAddress::Any, 1205);

    this->pHmiTecClient = nullptr;
    this->pHmiRobClient = nullptr;

    this->SignalSlotConnect();
}

HmiServer :: ~HmiServer(){
    delete pHmiRobClient;
    delete pHmiTecClient;
    delete pHmiRobServer;
    delete pHmiTecServer;
}

short HmiServer :: SignalSlotConnect(){
    connect(pHmiRobServer, SIGNAL(newConnection()),this,SLOT(onNewRobConnection()));
    connect(pHmiTecServer, SIGNAL(newConnection()),this,SLOT(onNewTecConnection()));
    return 1;
}

void HmiServer :: onNewRobConnection(){
    pHmiRobClient = pHmiRobServer->nextPendingConnection();
    connect(pHmiRobClient,SIGNAL(readyRead()),this,SLOT(onReadyRead_Client_RobController()));
}

void HmiServer :: onNewTecConnection(){
    pHmiTecClient = pHmiTecServer->nextPendingConnection();
    connect(pHmiTecClient,SIGNAL(readyRead()),this,SLOT(onReadyRead_Client_TecController()));
}

void  HmiServer::onReadyRead_Client_TecController(){
    QByteArray receiverawData;
    QByteArray sendData;
    if(this->HmiClientOrder == 1){
        receiverawData = this->pHmiTecClient->readAll();
        if(this->pTecControllerHMI != nullptr){
            this->pTecControllerHMI->fromBackendMessageCommand(receiverawData);
            this->pTecControllerHMI->toBackendMessage(sendData);
            this->pHmiTecClient->write(sendData);
        }
        else{
            sendData = "<Sender>HMISYSTEM</Sender><Hmi>NoPlugin</Hmi>";
            this->pHmiTecClient->write(sendData);
        }

    }
    else{
        receiverawData = this->pHmiTecClient->readAll();
        sendData = "<Sender>HMISYSTEM</Sender><Hmi>NotActive</Hmi>";
        this->pHmiTecClient->write(sendData);
    }
}

void  HmiServer::onReadyRead_Client_RobController(){
    QByteArray receiverawData;
    QByteArray sendData;
    if(this->HmiClientOrder == 2){
        receiverawData = this->pHmiRobClient->readAll();
        if(this->pRobControllerHMI != nullptr){
            this->pRobControllerHMI->fromBackendMessageCommand(receiverawData);
            this->pRobControllerHMI->toBackendMessage(sendData);
            this->pHmiRobClient->write(sendData);
        }
        else{
            sendData = "<Sender>HMISYSTEM</Sender><Hmi>NoRobot</Hmi>";
            this->pHmiRobClient->write(sendData);
        }

    }
    else{
        receiverawData = this->pHmiRobClient->readAll();
        sendData = "<Sender>HMISYSTEM</Sender><Hmi>NotActive</Hmi>";
        this->pHmiRobClient->write(sendData);
    }
}


